import axios from "axios";
import L from "leaflet";
import qs from "qs";
import cars, { location } from "@/assets/img.js";
import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import pinia from "@/store/pinia";
import { useMapStore } from "@/store/map";
const mapStore = useMapStore(pinia);

const getDateTime = (time) => {
  let dateTime = "";

  switch (time) {
    case "now":
      dateTime = new Date();
      break;
    case "today":
      dateTime = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
      break;
    case "week":
      dateTime = new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000);
      break;
    case "month":
      dateTime = new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000);
      break;
    default:
      dateTime = new Date();
  }

  // if (time === "now") {
  //   dateTime = new Date();
  // } else if (time === "today") {
  //   dateTime = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
  // } else if (time === "week") {
  //   dateTime = new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000);
  // } else if (time === "month") {
  //   dateTime = new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000);
  // }

  const year = dateTime.getFullYear();
  const month = (dateTime.getMonth() + 1).toString().padStart(2, "0");
  const day = dateTime.getDate().toString().padStart(2, "0");
  const hour = dateTime.getHours().toString().padStart(2, "0");
  const minute = dateTime.getMinutes().toString().padStart(2, "0");
  const second = dateTime.getSeconds().toString().padStart(2, "0");

  // "2024-07-11 00:00:00"
  return (
    year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second
  );
};

const setLocation = (map) => {
  axios
    .post(
      `http://65.29.3.198:60089/YzFatigueDriving/YzPljs/list`,
      qs.stringify({ rows: 100000, page: 1 }),
      {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      }
    )
    .then(
      (resp) => {
        if (resp.data.list === null) {
          return false;
        }
        // 清除所有的图层 begin
        const allLayers = map._layers; // 注意：_layers是一个内部属性，可能在未来版本中改变

        // 遍历所有图层，并检查它们是否是L.layerGroup的实例
        for (const layerId in allLayers) {
          const layer = allLayers[layerId];

          // 检查图层是否是L.layerGroup的实例
          if (layer instanceof L.LayerGroup) {
            // 如果是，则从地图上移除它
            map.removeLayer(layer);
          }

          // 注意：对于嵌套的layerGroup（即layerGroup中包含其他layerGroup）
        }

        const layerGroup = L.layerGroup().addTo(map);
        // 清除所有的图层 end

        // 绘图begin
        // let vehicleArr = [];
        // for (let i = 0; i < resp.data.list.length; i++) {
        //   vehicleArr.push({
        //     vehicleNo: resp.data.list[i].vehicleNo,
        //     endLat: resp.data.list[i].endLat,
        //     endLon: resp.data.list[i].endLon,
        //     shift: (resp.data.list[i].shift * 1000).toFixed(2) + "M"
        //   });
        // }

        console.log("所有车辆：");
        console.log(resp.data.list);

        for (let i = 0; i < resp.data.list.length; i++) {
          L.marker([resp.data.list[i]["endLat"], resp.data.list[i]["endLon"]], {
            icon: L.icon({
              iconUrl: location, // 图标图片的URL
              iconSize: [32, 32], // 图标的大小
              iconAnchor: [15, 15], // 图标的锚点，即图标的位置应该放置在地图上的位置
              popupAnchor: [-3, -76], // 弹出框的锚点，即当你点击图标时，弹出框应该出现在哪个位置
            }),
          })
            .addTo(layerGroup)
            .bindTooltip(
              resp.data.list[i]["vehicleNo"] +
                "（半径：" +
                (resp.data.list[i].shift * 1000).toFixed(2) +
                "M）",
              { permanent: true, direction: "top", color: "green", offset: [0, -20] }
            )
            .openTooltip();

          L.circle([resp.data.list[i]["endLat"], resp.data.list[i]["endLon"]], {
            stroke: true,
            dashArray: "4",
            color: "red",
            fillColor: "#f03",
            fillOpacity: 0.2,
            weight: 2,
            radius: 150 * Math.abs(resp.data.list[i].shift),
          }).addTo(layerGroup);
        }
        // 绘图end
      },
      (err) => {
        console.log(err);
        ElMessage({
          message: JSON.stringify(err),
          type: "error",
        });
      }
    );
};

const fetchBasicInfoData = (currentPage, pageSize) => {
  console.log("请求基本数据");

  axios
    .post(
      "http://65.29.3.198:60089/YzFatigueDriving/YzPljs/list",
      qs.stringify({ rows: pageSize, page: currentPage }),
      {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      }
    )
    .then(
      (resp) => {
        const resData = [];

        if (resp.data.list === null) {
          ElMessage({
            message: resp.data.msg,
            type: "info",
          });

          return false;
        }

        for (let i = 0; i < resp.data.list.length; i++) {
          resData.push({
            licensePlate: resp.data.list[i]["vehicleNo"],
            licenseType: resp.data.list[i]["vectype"],
            bracolor: resp.data.list[i]["bracolor"],
            veccolor: resp.data.list[i]["veccolor"],
            owner: resp.data.list[i]["cmcltname"],
            endLat: resp.data.list[i]["endLat"],
            endLon: resp.data.list[i]["endLon"],
            approvedLoadCapacity: resp.data.list[i]["chenum"],
            // nuclearTonnage: resp.data.list[i]["chenum"],
            authorizedSeatingCapacity: resp.data.list[i]["cheseats"],
          });
        }

        console.log("基本信息：");
        console.log(resp.data.list);

        mapStore.basicInfoTableData = resData;
        mapStore.basicInfoTableTotal = resp.data.pageInfo.totalRecord;
      },
      (err) => {
        console.log(err);
        ElMessage({
          message: JSON.stringify(err),
          type: "error",
        });
      }
    );
};

const fetchTrajectoryData = (licensePlate, currentPage, pageSize, time) => {
  console.log("请求轨迹数据");
  const formData = new FormData();
  formData.append("vehicleNo", licensePlate);
  formData.append("startDateTime", getDateTime(time));
  formData.append("endDateTime", getDateTime("now"));
  formData.append("rows", pageSize);
  formData.append("page", currentPage);
  axios
    .post(
      `http://65.29.3.198:60089/YzFatigueDriving/VehicleAll/list`,
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }
    )
    .then(
      (resp) => {
        const resData = [];
        for (let i = 0; i < resp.data.list.length; i++) {
          resData.push({
            vehicleNo: resp.data.list[i]["vehicleNo"],
            xc: resp.data.list[i]["xc"],
            startLon: resp.data.list[i]["startLon"],
            startLat: resp.data.list[i]["startLat"],
            endLon: resp.data.list[i]["endLon"],
            endLat: resp.data.list[i]["endLat"],
            minTime: resp.data.list[i]["minTime"],
            maxTime: resp.data.list[i]["maxTime"],
            drivingTime: resp.data.list[i]["drivingTime"] + "h",
          });
        }

        switch (time) {
          case "today":
            mapStore.trajectoryTodayTableData = resData;
            mapStore.trajectoryTodayTableTotal = resp.data.pageInfo.totalRecord;
            break;
          case "week":
            mapStore.trajectoryWeekTableData = resData;
            mapStore.trajectoryWeekTotal = resp.data.pageInfo.totalRecord;
            break;
          default:
            mapStore.trajectoryMonthTableData = resData;
            mapStore.trajectoryMonthTotal = resp.data.pageInfo.totalRecord;
        }
      },
      (err) => {
        console.log(err);
        ElMessage({
          message: JSON.stringify(err),
          type: "error",
        });
      }
    );
};

export { getDateTime, setLocation, fetchBasicInfoData, fetchTrajectoryData };
